﻿//存放报表单元格属性的MAP
var cellAttributeMap = new Map();

//存放报表区域的MAP
var reportCategoryMap = new Map();

//存放单元格是否是合并单元格
var cellIsMegerMap = new Map();
//存放合并单元格的种类
var hengbinCellMap = new Map();

var isDatabaseOnload = false;

//是否循环完了一个合并单元格
var isMegerCell = false;

//将所有字母set进MAP中，方便设置起始列和终止列的对应关系
//初始化的时候就加载，把所有字母放入到MAP中，好在设置数据区域的时候，对应相对的数字
//以字母为key的MAP
var letterMap = new Map();
//以数字为key的MAP
//为嘛分两种，为了数字和字母来回转换
var letterMapNum = new Map();
var letterArray = new Array("A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U",
		"V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI");
/*
 * absolutelyCol：绝对位置（列）
 * absolutelyRow：绝对位置（行）
 * relColNum：相对位置（列）
 * relRowNum:相对位置（行）
 * cellType：单元格类型（包括：自动生成、手动填写、计算、其他、预设）
 * presetType：预设指标的名称（包括：填报单位，填报时间，截止时间，起止时间）
 * isComment:是否需要批注，（1不需要，2需要），默认为1
 * areaType:区域属性
 * */
function Celldatatype(absolutelyCol,absolutelyRow,relColNum,relRowNum,cellType,presetType,isComment,areaType){
	this.absolutelyCol=absolutelyCol;
	this.absolutelyRow=absolutelyRow;
	this.relColNum=relColNum;
	this.relRowNum=relRowNum;
	this.cellType=cellType;
	this.presetType=presetType;
	this.isComment=isComment;
	this.areaType=areaType;
}

function CellIsMeger(col,row,hebing){
	this.col = col;
	this.row = row;
	this.hebing = hebing;
}
function Hebing(absCol,absRow){
	this.absCol = absCol;
	this.absRow = absRow;
}

/*
 * categoryId：统计信息集ID
 * categoryName：统计信息集名称
 * condStartCol：相对坐标起始列
 * condEndCol：相对坐标终止列
 * condStartRow：相对坐标起始行
 * condEndRow：相对坐标终止行
 * templateId：报表模板ID
 * absStartCol：绝对区域中的起始列
 * absEndCol：绝对区域中的终止列
 * absStartRow：绝对区域中的起始行
 * absEndRow：绝对区域中的终止行
 * temporaryDescribe:区域描述
 * */
function ReportCategory(categoryId,categoryName,condStartCol,condEndCol,condStartRow,condEndRow,templateId,absStartCol,absEndCol,absStartRow,absEndRow,temporaryDescribe){
	this.categoryId = categoryId;
	this.categoryName = categoryName;
	this.condStartCol = condStartCol;
	this.condEndCol = condEndCol;
	this.condStartRow = condStartRow;
	this.condEndRow = condEndRow;
	this.templateId = templateId;
	this.absStartCol = absStartCol;
	this.absEndCol = absEndCol;
	this.absStartRow = absStartRow;
	this.absEndRow = absEndRow;
	this.temporaryDescribe=temporaryDescribe;
}

function toRGB(color){
	var hh="";
    var kk=[];
    var reg=/^#([0-9a-zA-Z]{3})$/;
    if(color=="invalid") return "invalid";
    if(reg.test(color)) return color;
    for(var i=1;i<color.length;i+=2){ 
       hh=color.substr(i,2);
       var cc=parseInt(hh,16);
       kk.push(cc);
    }
    return kk;
}

function RGB(r, g, b) {
    return r | g << 8 | b << 16;
}

$(function(){
	
	var DCellWeb = document.getElementById("DCellWeb");
	DCellWeb.MenuStart = function(c,r,section){
		switch(section){
			case 1:
				DCellWeb.AddPopMenu(2001,"清除",0);
				DCellWeb.AddPopMenu(2004,"剪切",0);
				DCellWeb.AddPopMenu(2002,"复制",0);
				DCellWeb.AddPopMenu(2003,"粘贴",0);
				DCellWeb.AddPopMenu(2014,"自动换行",0);
				/*DCellWeb.AddPopMenu(1006,"添加表格批注",0);*/
				/*DCellWeb.AddPopMenu(1007,"单元格数据反查",0);*/
				DCellWeb.AddPopMenu(1008,"单元格条件定制",0);
				break;
			case 2:
				DCellWeb.AddPopMenu(2010,"插入行",0);
				DCellWeb.AddPopMenu(2011,"删除行",0);
				break;
			case 3:
				DCellWeb.AddPopMenu(2012,"插入列",0);
				DCellWeb.AddPopMenu(2013,"删除列",0);
				break;
			case 4:
				DCellWeb.AddPopMenu(1003,"表格左上角的单元格",0);
				break;
			case 5:
				DCellWeb.AddPopMenu(3001,"插入表页",0);
				DCellWeb.AddPopMenu(3002,"删除表页",0);
				break;
			case 6:
				DCellWeb.AddPopMenu(1005,"页签导航按钮区",0);
				break;
		}
	}
	
	DCellWeb.MenuCommand = function(c,r,itemId){
		switch(itemId){
			case 1006:
				setUpCellNotation(c,r);
				break;
			case 1007:
				alert("开始反查拉！");
				break;
			case 1008:
				//单元格条件定制
				cellConditionsLoad();
				break;
			case 3:
				DCellWeb.AddPopMenu(1003,"插入列",0);
				DCellWeb.AddPopMenu(1002,"删除列",0);
				break;
			case 4:
				DCellWeb.AddPopMenu(1003,"表格左上角的单元格",0);
				break;
			/*case 5:
				DCellWeb.AddPopMenu(1004,"页签区",0);
				break;*/
			case 6:
				DCellWeb.AddPopMenu(1005,"页签导航按钮区",0);
				break;
			case 2001:
				clearRange(c,r);
				break;
			case 2002:
				copyRange();
				break;
			case 2003:
				pasteRange(c,r);
				break;
			case 2004:
				cutRange();
				break;
			case 2012:
				insertColRange();
				break;
			case 2013:
				delColRange();
				break;
			case 2010:
				insertRowRange();
				break;
			case 2011:
				delRowRange();
				break;
			case 3001:
				reportInsertSheet();
				break;
			case 3002:
				reportDeleteSheet();
				break;
			case 2014:
				automaticNewline(c,r);
				break;
		}
	}
	
	function getCurCell(){
		var cell = {};
		cell.sheetNum = DCellWeb.GetCurSheet;
		cell.row = DCellWeb.GetCurrentRow;
		cell.col = DCellWeb.GetCurrentCol;
		return cell;
	}
	function getSelectRange(){
		var select = {};
		select.startCol = DCellWeb.GetSelectRangeJ(0);
		select.startRow = DCellWeb.GetSelectRangeJ(1);
		select.endCol = DCellWeb.GetSelectRangeJ(2);
		select.endRow = DCellWeb.GetSelectRangeJ(3);
		return select;
	}
	function getEveryCell(func){
		//获得选中起始行，列，终止行，列
		var qishilie = getSelectRange().startCol;
		var qishihang = getSelectRange().startRow;
		var zhongzhilie = getSelectRange().endCol;
		var zhongzhihang = getSelectRange().endRow;
		for(var a = qishilie; a < zhongzhilie+1;a++){
			for(var b = qishihang; b < zhongzhihang+1;b++){
				func(a,b);
			}
		}
	}
	
	function getFileType(){
		return $("#fileType").val();
	}
	$("#cellRowAndColBtn").click(function(){		
		alert("行:"+getCurCell().row+",列:"+getCurCell().col);
	});
	$("#inputTypeBtn").click(function(){
		var type = $("#inputType").val();
		DCellWeb.SetCellInput(getCurCell().col,getCurCell().row,getCurCell().sheetNum,type);
	});
	$("#selectRange").click(function(){
		alert("startRow:"+getSelectRange().startRow+",startCol:"+getSelectRange().startCol+",endRow:"+getSelectRange().endRow+",endCol:"+getSelectRange().endCol);
	});
	//合并单元格
	$("#mergeCell").click(function(){
		DCellWeb.MergeCells(getSelectRange().startCol,getSelectRange().startRow,getSelectRange().endCol,getSelectRange().endRow);
		
		var qishilie = getSelectRange().startCol;
		var qishihang = getSelectRange().startRow;
		var zhongzhilie = getSelectRange().endCol;
		var zhongzhihang = getSelectRange().endRow;
		
		var hebingStr = qishilie+"*"+qishihang+"*"+zhongzhilie+"*"+zhongzhihang;
		
		/*hengbinCellMap.put(hebing,"");*/
		
		for(var a=qishilie;a<= zhongzhilie;a++){
			for(var b=qishihang;b<=zhongzhihang;b++){
				var key = a+"**"+b;
				var cellIsMeger = new CellIsMeger(a,b,hebingStr);
				cellIsMegerMap.put(key,cellIsMeger);
			}
		}
	});
	//拆分单元格
	$("#unMergeCell").click(function(){
		DCellWeb.UnmergeCells(getSelectRange().startCol,getSelectRange().startRow,getSelectRange().endCol,getSelectRange().endRow);
		var cellIsMegerMap = new Map();
		var hengbinCellMap = new Map();
	});
	//字体样式设置
	$("#fontStyleCu").click(function(){
		getEveryCell(function(a,b){
			var fontIndex = DCellWeb.GetCellFontStyle(a,b,getCurCell().sheetNum);
			switch(fontIndex){
				case 0:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+2);
					break;
				case 2:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-2);
					break;
				case 4:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+2);
					break;
				case 6:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-2);
					break;
				case 8:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+2);
					break;
				case 10:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-2);
					break;
				case 12:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+2);
					break;
				case 14:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-2);
					break;
			}
		});
	});
	
	$("#fontStyleXie").click(function(){
		getEveryCell(function(a,b){
			var fontIndex = DCellWeb.GetCellFontStyle(a,b,getCurCell().sheetNum);
			switch(fontIndex){
				case 0:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+4);
					break;
				case 2:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+4);
					break;
				case 4:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-4);
					break;
				case 6:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-4);
					break;
				case 8:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+4);
					break;
				case 10:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+4);
					break;
				case 12:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-4);
					break;
				case 14:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-4);
					break;
			}
		});
	});
	
	$("#fontStyleXia").click(function(){
		getEveryCell(function(a,b){
			var fontIndex = DCellWeb.GetCellFontStyle(a,b,getCurCell().sheetNum);
			switch(fontIndex){
				case 0:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+8);
					break;
				case 2:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+8);
					break;
				case 4:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+8);
					break;
				case 6:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)+8);
					break;
				case 8:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-8);
					break;
				case 10:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-8);
					break;
				case 12:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-8);
					break;
				case 14:
					DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,parseInt(fontIndex)-8);
					break;
			}
		});
	});
	
	$("#fontStyleButton").click(function(){
	  $("#fontStyleDiv").toggle();
	});
	//清除字体样式设置
	$("#deletefontStyleButton").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellFontStyle(a,b,getCurCell().sheetNum,0);
		});
	});
	//字体设置
	$("#selectFont").change(function(){
		var fontValue = DCellWeb.FindFontIndex($("#selectFont").val(),1);
		getEveryCell(function(a,b){
			DCellWeb.SetCellFont(a,b,getCurCell().sheetNum,fontValue);
		});
	});
	//字体大小设置
	$("#selectFontSize").change(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellFontSize(a,b,getCurCell().sheetNum,$("#selectFontSize").val());
		});
	});
	//删除列
	$("#deleteCellCol").click(function(){
		var colDifferenceValue = parseInt(getSelectRange().endCol) - parseInt(getSelectRange().startCol) + 1;
		DCellWeb.DeleteCol(getSelectRange().startCol,colDifferenceValue,getCurCell().sheetNum);
	});
	
	//删除行
	$("#deleteCellRow").click(function(){
		var rowDifferenceValue = parseInt(getSelectRange().endRow) - parseInt(getSelectRange().startRow) + 1;
		DCellWeb.DeleteRow(getSelectRange().startRow,rowDifferenceValue,getCurCell().sheetNum);
	});
	
	//增加列
	$("#insertCellCol").click(function(){
		var colDifferenceValue = parseInt(getSelectRange().endCol) - parseInt(getSelectRange().startCol) + 1;
		DCellWeb.InsertCol(getSelectRange().startCol,colDifferenceValue,getCurCell().sheetNum);
	});
	
	//增加行
	$("#insertCellRow").click(function(){
		var rowDifferenceValue = parseInt(getSelectRange().endRow) - parseInt(getSelectRange().startRow) + 1;
		DCellWeb.InsertRow(getSelectRange().startRow,rowDifferenceValue,getCurCell().sheetNum);
	});
	
	//表格靠左
	$("#rowCellLeft").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,1);
		});
	});
	
	//表格居中
	$("#rowCellCenter").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,4);
		});
	});
	
	//表格居中
	$("#rowCellRight").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,2);
		});
	});
	
	//表格水平垂直居中
	$("#rowCellVerticalLevelCenter").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,36);
		});
	});
	
	//表格水平垂直靠上
	$("#rowCellVerticalLevelLeft").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,33);
		});
	});
	
	//表格水平垂直靠下
	$("#rowCellVerticalLevelRight").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,34);
		});
	});
	
	//表格分散对齐
	$("#rowCellDispersedAlignment").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,64);
		});
	});
	
	//设置表格边框线的粗细
	var borderSize = 2;
	$("#selectBorder").change(function(){
		borderSize = $("#selectBorder").val();
	});
	
	//表格设置
	$("#leftCellBorder").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,0,borderSize);
		});
	});
	
	$("#rightCellBorder").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,2,borderSize);
		});
	});
	
	$("#topCellBorder").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,1,borderSize);
		});
	});
	
	$("#downCellBorder").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,3,borderSize);
		});
	});
	
	$("#allCellBorder").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,0,borderSize);
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,2,borderSize);
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,1,borderSize);
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,3,borderSize);
		});
	});
	$("#allCellBorderNull").click(function(){
		getEveryCell(function(a,b){
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,0,1);
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,2,1);
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,1,1);
			DCellWeb.SetCellBorder(a,b,getCurCell().sheetNum,3,1);
		});
	});
	
	//设置背景颜色
	$("#chooseTextColor").colorpicker({
        fillcolor:true,
        success:function(o,color){
        	var colorValue = toRGB(color);
        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
        	getEveryCell(function(a,b){
    			DCellWeb.SetCellTextColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
    		});
        }
    });
	//右键清除区域内容
	function clearRange(a,b){
		getEveryCell(function(a,b){
			DCellWeb.clear(32);
			var key = a + "--" + b;
			cellAttributeMap.remove(key);
		});
	}
	//右键复制
	function cutRange(){
		DCellWeb.CutRange(getSelectRange().startCol,getSelectRange().startRow,getSelectRange().endCol,getSelectRange().endRow);
	}
	//右键复制
	function copyRange(){
		DCellWeb.CopyRange(getSelectRange().startCol,getSelectRange().startRow,getSelectRange().endCol,getSelectRange().endRow);
	}
	//右键粘贴
	function pasteRange(c,r){
		DCellWeb.Paste(c,r,0,0,0);
	}
	//右键插入列
	function insertColRange(){
		var colDifferenceValue = parseInt(getSelectRange().endCol) - parseInt(getSelectRange().startCol) + 1;
		DCellWeb.InsertCol(getSelectRange().startCol,colDifferenceValue,getCurCell().sheetNum);
	}
	//右键插入行
	function insertRowRange(){
		var rowDifferenceValue = parseInt(getSelectRange().endRow) - parseInt(getSelectRange().startRow) + 1;
		DCellWeb.InsertRow(getSelectRange().startRow,rowDifferenceValue,getCurCell().sheetNum);
	}
	//右键删除列
	function delColRange(){
		var colDifferenceValue = parseInt(getSelectRange().endCol) - parseInt(getSelectRange().startCol) + 1;
		DCellWeb.DeleteCol(getSelectRange().startCol,colDifferenceValue,getCurCell().sheetNum);
	}
	//右键删除行
	function delRowRange(){
		var rowDifferenceValue = parseInt(getSelectRange().endRow) - parseInt(getSelectRange().startRow) + 1;
		DCellWeb.DeleteRow(getSelectRange().startRow,rowDifferenceValue,getCurCell().sheetNum);
	}
	
	$("#import").click(function(){
		switch(getFileType()){
			case "1":
				DCellWeb.ImportExcelDlg();
				break;
			case "2":
				DCellWeb.ImportCSVFile();
				break;
		}		
	});
	$("#export").click(function(){
		switch(getFileType()){
			case "1":
				DCellWeb.ExportExcelDlg();
				break;
			case "2":
				DCellWeb.ExportCSVFile();
				break;
		}		
	});
	
	
	//报表保存
	$("#saveReportTemplate").click(function(){
		var templateId = $("#templateId").val();
		var annualId = $("#annualId").val();
		
		var reportCategoryText=JSON.stringify(reportCategoryMap);
		var jsonText=JSON.stringify(cellAttributeMap);
		var isSaveSuccess = DCellWeb.UploadFile(ctx+"/reportDesignController/saveReportTemplate/"+templateId+"/"+annualId);
		if(isSaveSuccess == '1'){
			$.ajax({
				   type: "POST",
				   url: ctx+"/reportDesignController/saveReportAllCellType/"+templateId+"/"+annualId,
				   data: {jsonText:jsonText,reportCategoryText:reportCategoryText},
				   success: function(){
					   alert("保存成功");
				   }
			}); 
		}else if(isSaveSuccess == '0'){
			alert("保存失败");
		}else{}
		
	});
	
	
	//设置单元格批注
	function setUpCellNotation(c,r){
    	parent.$.layer({
		    type: 2,
		    maxmin: true,
		    shadeClose: true,
		    title: '填写批注',
		    shade: [0.1,'#000000'],
		    offset: [($(window).height() / 4)+'px',''],
		    shadeClose: true,
		    area: ['300px', '150px'],
		    iframe: {src: ctx + '/test/setUpCellNotationAction'},
    		end: function(){
				var notationText = $("#notationValueId").val();
				DCellWeb.SetCellTip(c,r,getCurCell().sheetNum,notationText);
    		}
		}); 
    }
/* ----------------------------------报表区域设置------------------------------------------------------*/	
	for(var a = 0; a < letterArray.length; a++){
		letterMap.put(letterArray[a],parseInt(a)+parseInt(1));
		letterMapNum.put(parseInt(a)+parseInt(1),letterArray[a]);
	}
	function celldatatypeToString(celldatatype){
		alert(celldatatype.absolutelyCol+"**"+celldatatype.absolutelyRow+"**"+celldatatype.relativeCol+"**"+celldatatype.relativeRow+"**"+celldatatype.cellType+"**"+celldatatype.presetType);
	}

	//通过横纵坐标，获得单元格对象
	function getCellType(absolutelyCol,absolutelyRow){
		var key = absolutelyCol + "--" + absolutelyRow;
		var celldatatype = cellAttributeMap.get(key);
		return celldatatype;
	}
	
	//设置报表的绝对区域
	$("#setUpReportDataArea").click(function(){
		
		var areaType = $("#selectAreaType").val();
		if(areaType == '1'){
			tableInside();
		}else if(areaType == '2'){
			tableOutside();
		}else{}
		
	});
	
	//表内设置
	function tableInside(){
		if($("#reportCategorySelect").val() == null || $("#reportCategorySelect").val() == ""){
			alert("请选择所属区域");
			return false;
		}
		var areaType = $("#selectAreaType").val();
		if($("#startRow").val() == null || $("#startRow").val() == ""){
			alert("请输入起始行");
			return false;
		}
		if($("#endRow").val() == null || $("#endRow").val() == ""){
			alert("请输入终止行");
			return false;
		}
		if($("#startCol").val() == null || $("#startCol").val() == ""){
			alert("请输入起始列");
			return false;
		}
		if($("#endCol").val() == null || $("#endCol").val() == ""){
			alert("请输入终止列");
			return false;
		}
		
		//获得选中起始行，列，终止行，列
		var qishilie = getSelectRange().startCol;
		var qishihang = getSelectRange().startRow;
		var zhongzhilie = getSelectRange().endCol;
		var zhongzhihang = getSelectRange().endRow;
		
		//获得相对区域的起始列和终止列
		var relativeStartCol = $("#startCol").val();
		var relativeEndCol = $("#endCol").val();
		
		//将相对区域的中字母列转换成数字
		var relativeStartColNum = letterMap.get(relativeStartCol);
		var relativeEndColNum = letterMap.get(relativeEndCol);
		var relativeColDifference = parseInt(relativeEndColNum) - parseInt(relativeStartColNum) + 1;
		
		//获得相对区域的起始行和终止行
		var relativeStartRow = $("#startRow").val();
		var relativeEndRow = $("#endRow").val();
		var relativeRowDifference = parseInt(relativeEndRow) - parseInt(relativeStartRow) + 1;
		
		//算出绝对坐标的列差和行差  
		var absoluteRowDifference = parseInt(zhongzhihang) - parseInt(qishihang) + 1;
		var absoluteColDifference = parseInt(zhongzhilie) - parseInt(qishilie) + 1;
		
		if(relativeRowDifference != absoluteRowDifference){
			alert("填写的行值不符合数据区域中的行值");
			return false;
		}
		if(relativeColDifference != absoluteColDifference){
			alert("填写的列值不符合数据区域中的列值");
			return false;
		}
		var templateId = $("#templateId").val();
		//获得所选区域的ID和NAME
		var reportCategorySelectId = $("#reportCategorySelect").find("option:selected").val();
		var reportCategorySelectName = $("#reportCategorySelect").find("option:selected").text();
		
		var reportCategoryMapKey = randomString(true, 1, 32);
		var explain = "表内(列:"+relativeStartCol+"至"+relativeEndCol+"-行:"+relativeStartRow+"至"+relativeEndRow+")";
		/*if(areaType == '1'){
			explain="表内(列:"+relativeStartCol+"至"+relativeEndCol+"-行:"+relativeStartRow+"至"+relativeEndRow+")";
		}else if(areaType == '2'){
			explain="表外(列:"+qishilie+"至"+zhongzhilie+"-行"+qishihang+"至"+zhongzhihang+")";
		}*/
		var tableTr = handleReportCategory(reportCategoryMapKey,reportCategorySelectName,explain);
		$("#reportCategoryTable").append(tableTr);
		
		var reportCategory = new ReportCategory(reportCategorySelectId,reportCategorySelectName,relativeStartColNum,relativeEndColNum,relativeStartRow,relativeEndRow,templateId,qishilie,zhongzhilie,qishihang,zhongzhihang,explain);
		reportCategoryMap.put(reportCategoryMapKey,reportCategory);
		
		var dataRelativeStartRow = relativeStartRow;
		var dataRelativeStartColNum = relativeStartColNum;
		
		for(var a = qishilie; a < zhongzhilie+1;a++){
			if(parseInt(dataRelativeStartColNum) <= parseInt(relativeEndColNum)){
				for(var b = qishihang; b < zhongzhihang+1;b++){
					if(parseInt(dataRelativeStartRow) <= parseInt(relativeEndRow)){
						//alert(a+"**"+b+"**"+dataRelativeStartColNum+"**"+dataRelativeStartRow);
						var key = a + "--" + b;
						//alert(key + "**" + dataRelativeStartRow + "**" + dataRelativeStartColNum);
						var celldatatype = new Celldatatype(a,b,dataRelativeStartColNum,dataRelativeStartRow,"1","","1",areaType);
						dataRelativeStartRow++;
						cellAttributeMap.put(key,celldatatype);
						var colorValue = toRGB("#ffffcc");
			        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
						DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
					}
					else{
						dataRelativeStartRow = relativeStartRow;
						a=a-1;
						b=b-1;
						dataRelativeStartColNum = dataRelativeStartColNum - 1;
						break;
					}
				}
			}else{
				break;
			}
			dataRelativeStartColNum++;
		}
		alert("设置成功");
	}
	
	//表外设置
	function tableOutside(){
		var areaType = $("#selectAreaType").val();
		//获得选中起始行，列，终止行，列
		var qishilie = getSelectRange().startCol;
		var qishihang = getSelectRange().startRow;
		var zhongzhilie = getSelectRange().endCol;
		var zhongzhihang = getSelectRange().endRow;
		
		var templateId = $("#templateId").val();
		//获得所选区域的ID和NAME
		var reportCategorySelectId = $("#reportCategorySelect").find("option:selected").val();
		var reportCategorySelectName = $("#reportCategorySelect").find("option:selected").text();
		
		var reportCategoryMapKey = randomString(true, 1, 32);
		var explain = "表外(列:"+qishilie+"至"+zhongzhilie+"-行"+qishihang+"至"+zhongzhihang+")";
		var tableTr = handleReportCategory(reportCategoryMapKey,reportCategorySelectName,explain);
		$("#reportCategoryTable").append(tableTr);
		
		var reportCategory = new ReportCategory(reportCategorySelectId,reportCategorySelectName,'','','','',templateId,qishilie,zhongzhilie,qishihang,zhongzhihang,explain);
		reportCategoryMap.put(reportCategoryMapKey,reportCategory);
		
		for(var a = qishilie; a < zhongzhilie+1;a++){
			for(var b = qishihang; b < zhongzhihang+1;b++){
				var key = a + "--" + b;
				var celldatatype = new Celldatatype(a,b,'','',"1","","1",areaType);
				cellAttributeMap.put(key,celldatatype);
				var colorValue = toRGB("#ffffcc");
		    	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
			}
		}
		alert("设置成功");
	}
	
	//判断区域性质选择表内还是表外
	$("#selectAreaType").change(function(){
		var areaType = $("#selectAreaType").val();
		if(areaType == '2'){
			$("#areaColTr").hide();
			$("#areaRowTr").hide();
		}else{
			$("#areaColTr").show();
			$("#areaRowTr").show();
		}
	});
	
	//根据传进来的坐标，判断这个单元格是否是合并单元格，如果是合并单元格，先判断这个单元格有没有相对坐标
	function gaoyangwudi(col,row,xiangduilie,xiangduihang){
		var isMegerKey = col+"**"+row;
		var cellIsMeger = cellIsMegerMap.get(isMegerKey);
		var hebing = hengbinCellMap.get(cellIsMeger.hebing);
		return hebing;
	}
	
	//点击单元格触发该事件
	DCellWeb.MouseLClick = function(c,r,updn){
		var key = c+"--"+r;
		var celldatatype = cellAttributeMap.get(key);
		if(celldatatype != null){
			//alert(celldatatypeToString(cellAttributeMap.get(key)));
			//判断报表单元格属性
			if(celldatatype.cellType == "1"){
				$("#selectCellRegionalValue option[value='1']").attr("selected", "selected"); 
				$("#presetTypeTr").hide();
			}else if(celldatatype.cellType == "2"){
				$("#selectCellRegionalValue option[value='2']").attr("selected", "selected"); 
				$("#presetTypeTr").hide();
			}else if(celldatatype.cellType == "3"){
				$("#selectCellRegionalValue option[value='3']").attr("selected", "selected"); 
				$("#presetTypeTr").hide();
			}else if(celldatatype.cellType == "4"){
				$("#selectCellRegionalValue option[value='4']").attr("selected", "selected"); 
				$("#presetTypeTr").hide();
			}else if(celldatatype.cellType == "5"){
				$("#selectCellRegionalValue option[value='5']").attr("selected", "selected");
				$("#presetTypeTr").show();
				if(celldatatype.presetType != null && celldatatype.presetType != ""){
					$("#presetTypeSelectValue option[value='" + celldatatype.presetType + "']").attr("selected", "selected");
				}
			}else if(celldatatype.cellType == "7"){
				$("#selectCellRegionalValue option[value='7']").attr("selected", "selected"); 
				$("#presetTypeTr").hide();
			}else{
				$("#selectCellRegionalValue option[value='0']").attr("selected", "selected");
				$("#presetTypeTr").hide();
			}
			//判断是否需要批注
			if(celldatatype.isComment == "1"){
				$("#isNeedCommentId option[value='1']").attr("selected", "selected");
			}else if(celldatatype.isComment == "2"){
				$("#isNeedCommentId option[value='2']").attr("selected", "selected");
			}else{
				$("#isNeedCommentId option[value='2']").attr("selected", "selected");
			}
		}else{
			$("#selectCellRegionalValue option[value='0']").attr("selected", "selected");
			$("#presetTypeTr").hide();
			$("#isNeedCommentId option[value='1']").attr("selected", "selected");
		}
	}
	
	//按下DEL键，清除选中单元格的所有属性
	document.onkeydown=function(event){
		var e = event || window.event || arguments.callee.caller.arguments[0];
        if(e && e.keyCode==46){ // delete
        	getEveryCell(function(a,b){
        		var key = a + "--" + b;
    			cellAttributeMap.remove(key);
    			DCellWeb.clear(32);
    		});
        }
    }; 
	
	//下拉框设置单元格属性
	$("#selectCellRegionalValue").change(function(){
		var selectValue = $("#selectCellRegionalValue").val();
		getEveryCell(function(a,b){
			var key = a + '--' + b;
			var celldatatype = cellAttributeMap.get(key);
			if(selectValue == "1"){
				if(celldatatype == null){
					var celldatatype = new Celldatatype(a,b,"","","1","","1","");
				}else{
					celldatatype.cellType="1";
				}
				cellAttributeMap.put(key,celldatatype);
				var colorValue = toRGB("#FFFFCC");
	        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
				$("#presetTypeTr").hide();
				//判断如果从预设变成别的单元格属性，要清除该单元格中的预设值
				DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"");
			}else if(selectValue == "2"){
				if(celldatatype == null){
					var celldatatype = new Celldatatype(a,b,"","","2","","1","");
				}else{
					celldatatype.cellType="2";
				}
				cellAttributeMap.put(key,celldatatype);
				var colorValue = toRGB("#99FF99");
	        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
				$("#presetTypeTr").hide();
				//判断如果从预设变成别的单元格属性，要清除该单元格中的预设值
				DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"");
			}else if(selectValue == "3"){
				if(celldatatype == null){
					var celldatatype = new Celldatatype(a,b,"","","3","","1","");
				}else{
					celldatatype.cellType="3";
				}
				cellAttributeMap.put(key,celldatatype);
				var colorValue = toRGB("#66FFFF");
	        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
				$("#presetTypeTr").hide();
				//判断如果从预设变成别的单元格属性，要清除该单元格中的预设值
				DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"");
			}else if(selectValue == "4"){
				if(celldatatype == null){
					var celldatatype = new Celldatatype(a,b,"","","4","","1","");
				}else{
					celldatatype.cellType="4";
				}
				cellAttributeMap.put(key,celldatatype);
				var colorValue = toRGB("#EAEAEA");
	        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
				$("#presetTypeTr").hide();
				//判断如果从预设变成别的单元格属性，要清除该单元格中的预设值
				DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"");
			}else if(selectValue == "5"){
				if(celldatatype == null){
					var celldatatype = new Celldatatype(a,b,"","","5","","1","");
				}else{
					celldatatype.cellType="5";
				}
				cellAttributeMap.put(key,celldatatype);
				var colorValue = toRGB("#C1CDC1");
	        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
				$("#presetTypeTr").show();
			}else if(selectValue == "7"){
				if(celldatatype == null){
					var celldatatype = new Celldatatype(a,b,"","","7","","1","");
				}else{
					celldatatype.cellType="7";
				}
				cellAttributeMap.put(key,celldatatype);
				$("#presetTypeTr").hide();
				var colorValue = toRGB("#E1E0E0");
	        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
				DCellWeb.SetCellBackColor(a,b,getCurCell().sheetNum,DCellWeb.FindColorIndex(colorIndex,1));
				//判断如果从预设变成别的单元格属性，要清除该单元格中的预设值
				DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"");
				DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"--");
				DCellWeb.SetCellAlign(a,b,getCurCell().sheetNum,4);
			}
			else{}
		});
	});
	
	//当选择预设下拉框时，给当前单元格赋值
	$("#presetTypeSelectValue").change(function(){
		//获得当前选中的预设下拉框
		var presetTypeName = $("#presetTypeSelectValue").find("option:selected").text();
		var presetTypeValue = $("#presetTypeSelectValue").val();
		
		getEveryCell(function(a,b){
			//给当前单元格赋值
			DCellWeb.SetCellString(a,b,getCurCell().sheetNum,"{"+presetTypeName+"}");
			//选择预设后，需要得到这个单元格的KEY，获取MAP下的这个实体，然后给它赋值
			var key = a + "--" + b;
			var celldatatype = cellAttributeMap.get(key);
			celldatatype.presetType = presetTypeValue;
		});
	});

	/* ----------------------------------报表区域设置------------------------------------------------------*/	
	
	//行列条件设置的DIV拖动代码
	$(".conditionsLiClass").mousedown(function (event) {
		var isMove = true;  
        var abs_x = event.pageX - $('.hanglietiaojian').offset().left;  
        var abs_y = event.pageY - $('.hanglietiaojian').offset().top;  
        $(document).mousemove(function (event) {  
                    if (isMove) {  
                        var obj = $('.hanglietiaojian');  
                        obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y});  
                        var obj1 = $('.hanglietiaojianFrame'); 
                        obj1.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y}); 
                    }  
                }  
        ).mouseup(  
                function () {  
                    isMove = false;  
                }  
        );  
	});
	
	//单元格条件加载
	function cellConditionsLoad(){
		$("#celltiaojianTable tr:gt(0)").remove();
		$.ajax({
			url:ctx+'/reportTemplateConditionsController/getAllDataSet',
			type:'POST',
			cache:false,
			success:function(data){
				var dataSetOptions = "";
			    $.each(data,function(idx,item){
			    	dataSetOptions += "<option value='" + item.id + "'>" + item.chineseName + "</option>";
				});
			    $("#dataSetSelectCell option").remove();
			    dataSetOptionsFirst="<option value='0'>请选择</option>";
			    $(".dataSetSelectCellClass").append(dataSetOptionsFirst).append(dataSetOptions);
			    DivSetVisibleCellCond(true);
			}
		});
		
		var row = getCurCell().row;
		var col = getCurCell().col;
		var templateId = $("#templateId").val();
		
		$("#cellHangNum").val(row);
		$("#cellLieNum").val(col);
		
		$.ajax({
			url:ctx+'/reportTemplateConditionsController/getCellCondByTemplateId/'+templateId+"/"+row+"/"+col,
			type:'POST',
			cache:false,
			success:function(data){
			    $.each(data,function(idx,item){
			    	var tableTr = handleDataCell(item.absRowNum,item.absColNum,item.chineseName,item.itemChineseName,item.jspRelaOperatorShow,item.jspComboTypeShow,item.conditionVal,item.jspLogicOperatorShow,item.conditionId);
			    	$("#celltiaojianTable").append(tableTr);
			    	var cellShiTi = new CellShiTi(item.absRowNum,item.absColNum,item.setId,item.itemId,item.relaOperator,item.comboType,item.conditionVal,item.logicOperator);
			    	celltiaojianMap.put(item.conditionId,cellShiTi);
				});
			}
		});
	}
	
	//单元格条件DIV拖动
	$(".conditionCellLiClass").mousedown(function (event) {
		var isMove = true;  
        var abs_x = event.pageX - $('.danyuangetiaojian').offset().left;  
        var abs_y = event.pageY - $('.danyuangetiaojian').offset().top;  
        $(document).mousemove(function (event) {  
                    if (isMove) {  
                        var obj = $('.danyuangetiaojian');  
                        obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y});  
                        var obj1 = $('.danyuangetiaojianFrame'); 
                        obj1.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y}); 
                    }  
                }  
        ).mouseup(  
                function () {  
                    isMove = false;  
                }  
        );  
	});
	
	//行列计算的DIV拖动
	$(".countLiClass").mousedown(function (event) {
		var isMove = true;  
        var abs_x = event.pageX - $('.hangliejisuanClass').offset().left;  
        var abs_y = event.pageY - $('.hangliejisuanClass').offset().top;  
        $(document).mousemove(function (event) {  
                    if (isMove) {  
                        var obj = $('.hangliejisuanClass');  
                        obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y});  
                        var obj1 = $('.hangliejisuanFrameClass'); 
                        obj1.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y}); 
                    }  
                }  
        ).mouseup(  
                function () {  
                    isMove = false;  
                }  
        );  
	});
	
	//行列校核的DIV拖动
	$(".validationLiClass").mousedown(function (event) {
		var isMove = true;  
        var abs_x = event.pageX - $('.hangliejiaoheClass').offset().left;  
        var abs_y = event.pageY - $('.hangliejiaoheClass').offset().top;  
        $(document).mousemove(function (event) {  
                    if (isMove) {  
                        var obj = $('.hangliejiaoheClass');  
                        obj.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y});  
                        var obj1 = $('.hangliejiaoheFrameClass'); 
                        obj1.css({'left':event.pageX - abs_x, 'top':event.pageY - abs_y}); 
                    }  
                }  
        ).mouseup(  
                function () {  
                    isMove = false;  
                }  
        );  
	});
	
	//是否需要批注
	$("#isNeedCommentId").change(function(){
		var key = getCurCell().col + "--" + getCurCell().row;
		var celldatatype = cellAttributeMap.get(key);
		if(celldatatype == null){
			alert("请先设置单元格属性");
			return false;
		}
		var isNeedCommentValue = $("#isNeedCommentId").val();
		if(isNeedCommentValue == '1'){
			if(getSelectRange().startCol == getSelectRange().endCol && getSelectRange().startRow == getSelectRange().endRow){
				var colorValue = toRGB("#000000");
		    	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
		    	DCellWeb.DrawGridLine(getSelectRange().startCol,getSelectRange().startRow,getSelectRange().endCol,getSelectRange().endRow,0,2,DCellWeb.FindColorIndex(colorIndex,1));
				//修改报表单元格实体中的属性
				var key = getCurCell().col + "--" + getCurCell().row;
				var celldatatype = cellAttributeMap.get(key);
				celldatatype.isComment = "1";
			}else{
				alert("请选择一个单元格");
				return false;
			}
		}else{
			if(getSelectRange().startCol == getSelectRange().endCol && getSelectRange().startRow == getSelectRange().endRow){
				var colorValue = toRGB("#0000FF");
		    	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
		    	DCellWeb.DrawGridLine(getSelectRange().startCol,getSelectRange().startRow,getSelectRange().endCol,getSelectRange().endRow,0,3,DCellWeb.FindColorIndex(colorIndex,1));
				//修改报表单元格实体中的属性
				var key = getCurCell().col + "--" + getCurCell().row;
				var celldatatype = cellAttributeMap.get(key);
				celldatatype.isComment = "2";
			}else{
				alert("请选择一个单元格");
				return false;
			}
			
		}
	});
	
	//插入表页
	function reportInsertSheet(){
		DCellWeb.InsertSheet(1,1);
	}
	//删除表页
	function reportDeleteSheet(){
		DCellWeb.DeleteSheet(1,1);
	}
	//自动换行
	function automaticNewline(col,row){
		DCellWeb.SetCellTextStyle(col,row,getCurCell().sheetNum,2);
	}
});


function onloadReportCategory(){
	$.ajax({
		url:ctx+'/reportStatCategoryController/getAllReportStatCategory',
		type:'POST',
		cache:false,
		success:function(data){
			var dataSetOptions = "";
		    $.each(data,function(idx,item){
		    	dataSetOptions += "<option value='" + item.id + "'>" + item.categoryName + "</option>";
			});
		    $("#reportCategorySelect option").remove();
		    dataSetOptionsFirst="<option value=''>请选择</option>";
		    $(".reportCategorySelectClass").append(dataSetOptionsFirst).append(dataSetOptions);
		}
	});
}

//删除一个报表数据区域
function deleteReportCategoryTableTr(obj){
	var id=$(obj).parent().attr('id');
	//删除表格里面的TR
	$('#'+id).parent().remove();
	var reportCategory = reportCategoryMap.get(id);
	//删除这个区域下的所有坐标
	for(var a = reportCategory.absStartCol;a < parseInt(reportCategory.absEndCol)+1;a++){
		for(var b = reportCategory.absStartRow;b<parseInt(reportCategory.absEndRow)+1;b++){
			var key = a + "--" + b;
			cellAttributeMap.remove(key);
			var colorValue = toRGB("#FFFFFF");
        	var colorIndex = RGB(colorValue[0],colorValue[1],colorValue[2]);
			DCellWeb.SetCellBackColor(a,b,0,DCellWeb.FindColorIndex(colorIndex,1));
		}
	}
	//删除当前区域
	reportCategoryMap.remove(id);
}

//具体实现方法(数据区域)
function handleReportCategory(mapkey,reportCategorySelectName,explain){
	var tr = '<tr id="' + mapkey + 'Tr">';
    tr += '<td align="center" valign="middle" class="td_grey2">' + reportCategorySelectName + '</td>';  
    tr += '<td align="center" valign="middle" class="td_grey2">' + explain + '</td>';  
    tr += '<td align="center" valign="middle" class="td_grey2" id="' + mapkey + '"><a href="#" onclick="deleteReportCategoryTableTr(this)">删除</a>';
    tr += '</tr>';
    return tr;  
}